import hashlib
import re
from urllib.parse import quote
import bencodepy


def parse_torrent_file(file_path):
    """解析Torrent文件并返回解码后的内容"""
    try:
        with open(file_path, 'rb') as f:
            torrent = f.read()
        return torrent
    except FileNotFoundError:
        print(f"错误：找不到文件 '{file_path}'")
        return None
    except Exception as e:
        print(f"解析文件时出错: {e}")
        return None


def torrent_encode(torrent_data):
    try:
        return bencodepy.encode(torrent_data)
    except Exception as e:
        print(f"编码失败: {e}")
        return None


def torrent_decode(torrent):
    try:
        return bencodepy.decode(torrent)
    except Exception as e:
        print(f"解码失败: {e}")
        return None


def validate_announce(announce_url):
    pattern = r"^(http|udp)://.*:6969/announce\?.*passkey="
    return re.match(pattern, announce_url) is not None


def torrent_passkey_modify(torrent, passkey):
    torrent_data = torrent_decode(torrent)
    if not torrent_data:
        return None

    announce = torrent_data[b"announce"].decode("utf-8")
    if validate_announce(announce):
        # 直接分割字符串替换 passkey
        parts = announce.split('passkey=')
        if len(parts) == 2:
            new_announce = f'{parts[0]}passkey={quote(passkey)}'
            torrent_data[b"announce"] = new_announce.encode("utf-8")
            return torrent_encode(torrent_data)
    return None



def parser(torrent):
    torrent_data = torrent_decode(torrent)

    torrent_info = torrent_data[b"info"]

    total_length = 0
    if b"length" in torrent_info:
        total_length = torrent_info[b"length"]
    elif b"files" in torrent_info:
        total_length = sum(f[b"length"] for f in torrent_info[b"files"])
    else:
        raise ValueError("无效的Torrent结构")

    info_hash = hashlib.sha1(bencodepy.encode(torrent_info)).digest()

    # hash_info = bencodepy.encode(torrent_info)

    # return total_length, info_hash, hash_info
    return total_length, info_hash


def save_torrent_file(torrent, output_path):
    """将Torrent数据保存到文件"""
    try:
        with open(output_path, 'wb') as f:
            f.write(torrent)
        print(f"Torrent文件已保存到: {output_path}")
        return True
    except Exception as e:
        print(f"保存文件时出错: {e}")
        return False


if __name__ == '__main__':
    torrent = parse_torrent_file("I:/PythonWorkSpace/PTServiceApplication/response.torrent")
    total_length, info_hash, hash_info = parser(torrent)
    # torrent = torrent_passkey_modify(torrent, "new_passkey")
    print(f"[{total_length}], [{info_hash}], [{hash_info}]")

# == = key == =
# b'announce':
# b'comment':
# b'created by':
# b'creation date':
# b'info':
# b'length' ==
# b'name' ==
# b'piece length' ==
# b'pieces' ==
# b'private' ==
#
# == = Torrent
# Info == =
# 名称: 录制 - 24662740 - 20250409 - 202913 - 217 - 关税与和平珍珠计划.flv
# 大小: 3.04
# GB
# announce: http: // 127.0
# .0
# .1: 6969 / announce?passkey = new_passkey
# created
# by: qBittorrent
# v5
# .1
# .0
# 创建时间: 2025 - 05 - 18
# 11: 11:56
# 注释: test
# == == == == == == == == == == ==
